﻿using System.Collections.Generic;
using UnityEngine;

namespace Fish.Utility
{
	public class GameObjectPool
	{
		public class Pool : Queue<GameObject> { }

		private IDictionary<GameObject, Pool> unuseDic = new Dictionary<GameObject, Pool>();
		private IDictionary<GameObject, Pool> useDic = new Dictionary<GameObject, Pool>();

		public GameObject this[string path]
		{
			get
			{
				return Get(path);
			}
		}

		public GameObject this[GameObject resource]
		{
			get
			{
				return Get(resource);
			}
		}

		private GameObjectPool() { }

		public static GameObjectPool Create()
		{
			return new GameObjectPool();
		}

		private GameObject Get(string path)
		{
			return Get(Resources.Load(path) as GameObject);
		}

		private GameObject Get(GameObject resource)
		{
			Pool pool;
			GameObject source;

			if (!unuseDic.TryGetValue(resource, out pool))
				unuseDic.Add(resource, pool = new Pool());

			source = pool.Count <= 0 ? GameObject.Instantiate(resource) as GameObject : pool.Dequeue();
			source.SetActive(true);

			useDic.Add(source, pool);

			return source;
		}

		public void Release(GameObject source)
		{
			if (!useDic.ContainsKey(source))
				return;

			source.SetActive(false);

			useDic[source].Enqueue(source);
			useDic.Remove(source);
		}
	}
}
